package com.retrofit.demo;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;

import com.breeze.toolkit.retrofit.APIRequestCallback;
import com.breeze.toolkit.retrofit.RetrofitAPIRequest;
import com.breeze.toolkit.ui.BaseActivity;
import com.breeze.toolkit.util.APIUtil;
import com.breeze.toolkit.util.ConstantsUtil;
import com.breeze.toolkit.util.ToastUtil;
import com.retrofit.demo.api.OauthToken;
import com.retrofit.demo.api.RetrofitEnum;

import retrofit.Retrofit;

public class MainActivity extends BaseActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
		fab.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
						.setAction("Action", null).show();
				test();
			}
		});
	}

	private void test() {
		String encode = Base64.encodeToString(ConstantsUtil.AUTHORIZATION_CONTENT.getBytes(), Base64.NO_WRAP);
		RetrofitEnum.getInterceptor().setHeaderMap(APIUtil.getSignOrQueryMap(
				new String[] {
						ConstantsUtil.AUTHORIZATION, ConstantsUtil.CONTENT_TYPE
				},
				new String[] {
						ConstantsUtil.AUTHORIZATION_BASIC + encode.trim(), ConstantsUtil.CONTENT_FORM
				}
		));

		RetrofitAPIRequest.request(this, RetrofitEnum.getAPIService().login(APIUtil.getSignOrQueryMap(
				new String[] {
						ConstantsUtil.GRANT, ConstantsUtil.USERNAME, ConstantsUtil.PASSWORD
				}, new String[] {
						ConstantsUtil.PASSWORD, "13912345678", "qqqqqq"
				})),
				new APIRequestCallback<OauthToken>() {
					@Override
					public void onServerBusinessSuccess(OauthToken data, Retrofit retrofit) {
						if (!TextUtils.isEmpty(data.getAccessToken())) {
							ToastUtil.show(getApplicationContext(), data.getAccessToken());
						}
					}

					@Override
					public void onServerBusinessFailed(OauthToken data, Retrofit retrofit) {

					}

					@Override
					public void onServerFailure(Throwable t) {

					}
				}, true, this);
	}

	@Override
	public void refreshRequest() {
		test();
	}

	@Override
	public int getLayoutId() {
		return R.layout.activity_main;
	}

	@Override
	public Object getViewTitle() {
		return R.string.app_name;
	}
}
